<template>
  <div class="products-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品管理</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索产品"
              style="width: 200px; margin-right: 10px"
            />
            <el-button type="primary" @click="handleAddProduct">添加产品</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredProducts" style="width: 100%">
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="category" label="类别" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="price" label="采购价格">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="库存情况">
          <template #default="{ row }">
            <el-popover
              placement="right"
              :width="400"
              trigger="click"
            >
              <template #reference>
                <el-button type="primary" link>查看库存</el-button>
              </template>
              <div class="stock-info">
                <h4>各仓库库存情况</h4>
                <el-table :data="row.stockInfo" size="small">
                  <el-table-column prop="warehouse" label="仓库" />
                  <el-table-column prop="currentStock" label="当前库存" />
                  <el-table-column prop="minStock" label="最低库存" />
                  <el-table-column prop="status" label="状态">
                    <template #default="{ row }">
                      <el-tag :type="getStockStatusType(row.status)">
                        {{ row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleQuickPurchase(row)">快速采购</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑产品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑产品' : '添加产品'"
      width="500px"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="productForm.category" placeholder="选择类别">
            <el-option label="水果" value="水果" />
            <el-option label="蔬菜" value="蔬菜" />
            <el-option label="肉类" value="肉类" />
            <el-option label="海鲜" value="海鲜" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="productForm.unit" />
        </el-form-item>
        <el-form-item label="采购价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="productForm.minStock" :min="0" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="productForm.supplier" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 快速采购对话框 -->
    <el-dialog
      v-model="purchaseDialogVisible"
      title="快速采购"
      width="500px"
    >
      <el-form
        ref="purchaseForm"
        :model="purchaseForm"
        :rules="purchaseRules"
        label-width="100px"
      >
        <el-form-item label="产品名称">
          <span>{{ currentProduct?.name }}</span>
        </el-form-item>
        <el-form-item label="供应商">
          <span>{{ currentProduct?.supplier }}</span>
        </el-form-item>
        <el-form-item label="采购数量" prop="quantity">
          <el-input-number 
            v-model="purchaseForm.quantity" 
            :min="1" 
            :step="10"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="目标仓库" prop="warehouse">
          <el-select
            v-model="purchaseForm.warehouse"
            placeholder="选择仓库"
            clearable
            style="width: 200px"
          >
            <el-option label="北京仓库" value="北京仓库" />
            <el-option label="上海仓库" value="上海仓库" />
            <el-option label="广州仓库" value="广州仓库" />
          </el-select>
        </el-form-item>
        <el-form-item label="预计到货" prop="expectedDate">
          <el-date-picker
            v-model="purchaseForm.expectedDate"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="purchaseForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePurchaseSubmit">确认采购</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useProductStore } from '../../stores/productStore'
import { nextTick } from 'vue'

// 搜索查询
const searchQuery = ref('')
const store = useProductStore()
const productFormRef = ref(null)

// 仓库列表
const warehouses = [
  { id: 1, name: '北京仓库' },
  { id: 2, name: '上海仓库' },
  { id: 3, name: '广州仓库' }
]

// 在组件挂载时初始化 store
onMounted(() => {
  store.initialize()
})

// 过滤后的产品列表
const filteredProducts = computed(() => {
  if (!searchQuery.value) return store.products
  const query = searchQuery.value.toLowerCase()
  return store.products.filter(product => 
    product.name.toLowerCase().includes(query) ||
    product.category.toLowerCase().includes(query) ||
    product.supplier.toLowerCase().includes(query)
  )
})

// 添加/编辑对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const productForm = ref({
  id: null,
  name: '',
  category: '',
  unit: '',
  price: 0,
  minStock: 0,
  supplier: '',
  stockInfo: []
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类别', trigger: 'change' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  price: [{ required: true, message: '请输入采购价格', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }],
  supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }]
}

// 处理添加产品
const handleAddProduct = () => {
  isEdit.value = false
  productForm.value = {
    id: null,
    name: '',
    category: '',
    unit: '',
    price: 0,
    minStock: 0,
    supplier: '',
    stockInfo: warehouses.map(w => ({
      warehouse: w.name,
      currentStock: 0,
      minStock: 0,
      status: '正常'
    }))
  }
  dialogVisible.value = true
}

// 处理编辑产品
const handleEdit = (row) => {
  isEdit.value = true
  productForm.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// 处理删除产品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除产品 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    store.deleteProduct(row.id)
    ElMessage.success('删除成功')
  })
}

// 提交保存
const handleSubmit = () => {
  if (isEdit.value) {
    store.updateProduct(productForm.value)
    ElMessage.success('更新成功')
  } else {
    productForm.value.id = Date.now()
    store.addProduct(productForm.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
}

// 库存状态样式
const getStockStatusType = (status) => {
  const types = {
    '库存不足': 'danger',
    '正常': 'success',
    '库存过高': 'warning'
  }
  return types[status] || 'info'
}

// 快速采购
const purchaseDialogVisible = ref(false)
const currentProduct = ref(null)
const purchaseForm = ref({
  quantity: 1,
  warehouse: '',
  expectedDate: null,
  remark: ''
})

const purchaseRules = {
  quantity: [{ required: true, message: '请输入采购数量', trigger: 'blur' }],
  warehouse: [{ required: true, message: '请选择目标仓库', trigger: 'change' }],
  expectedDate: [{ required: true, message: '请选择预计到货日期', trigger: 'change' }]
}

// 处理快速采购
const handleQuickPurchase = (row) => {
  const defaultWarehouse = row.stockInfo.length > 0 ? row.stockInfo[0].warehouse : '北京仓库'
  purchaseForm.value = {
    quantity: 1,
    warehouse: defaultWarehouse,
    expectedDate: null,
    remark: ''
  }
  currentProduct.value = row
  purchaseDialogVisible.value = true
}


// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 处理采购提交
const handlePurchaseSubmit = () => {
  console.log('采购表单数据:', purchaseForm.value)
  ElMessage.success('采购订单已创建')
  purchaseDialogVisible.value = false
}
</script>

<style scoped>
.products-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.stock-info {
  padding: 10px;
}

.stock-info h4 {
  margin-bottom: 15px;
  color: #303133;
}
</style>